<template>
  <div class="sdy-self">
    <SdyHeader title="啥都有-个人中心" back></SdyHeader>
    <!-- 空状态 -->
    <van-empty
    v-if='!inLogin'
     description="您还没有登录">
      <van-button 
      @click="$router.push('/login')"
      round type="danger" class="bottom-button">登录</van-button>
    </van-empty>

    <div 
    v-else
    class="sdy-self-info">
      <div class="self-img">
        <van-image
          round
          width="5rem"
          height="5rem"
          :src="avatar"
        />
        <p class='user-name'>昵称:{{nickname}}</p>
        <div class="info">
        <van-icon name="setting-o" @click="$router.push('/admin')" size='20px'></van-icon>

        </div>
      </div>

      <div class='self-gol'>
        <p>我的工具</p>
        <van-grid>
          <van-grid-item @click="$router.push('/cart')" icon="shopping-cart" text="购物车" />
          <van-grid-item to="/order" icon="todo-list" text="订单" />
          <van-grid-item icon="location" text="收货地址" />
          <van-grid-item icon="smile" dot text="退款/售后" />
        </van-grid>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {useRouter,type Router} from 'vue-router';
import {onMounted,ref} from 'vue'
import {getUserInfoApi} from '@/api/users'
const $router:Router = useRouter()
//空状态


  // 从localStorage内拿到token验证
  //如果没有说明没有登录过
  const token = window.localStorage.getItem('token')
  const user_id = window.localStorage.getItem('user_id')

//表示是否登录
const inLogin = ref<boolean>(false)
//1.验证token
const testToken = async () => {
  if(!token || !user_id){
    inLogin.value = false
  }
  //如果有说明登录过，但是可能登录已经过期
  // 根据id和token请求信息
  const res = await getUserInfoApi(user_id as string)
  //判断结果 10019
  if(((res as unknown) as {code:string}).code === '10019'){
    inLogin.value = false
    return
  }

  //表示登录过
  inLogin.value = true
}

//获取用户信息
const avatar = ref<string>('')
const nickname = ref<string>('')
const getUserInfo = async (id :string)=>{
  const res = await getUserInfoApi(id)
  avatar.value = res.data.avatar
  nickname.value = res.data[0].nickname
}


onMounted(()=>{
  getUserInfo(user_id as string)
  testToken()
})
</script>

<style scoped lang="scss">
  .bottom-button {
    width: 160px;
    height: 40px;
  }
  .self-img{
    margin: 5px 5px;
    display: flex;
    justify-content: space-between;
    > .user-name{
      width: 150px;
      margin-right:100px;
      line-height: 50px;
    }
    > .info{
      margin: 5px;
    }
  }
  > .self-gol{
 --van-grid-item-content-background-color: red;

  }
</style>
